<?php
/**
 * @see Alinks_Zip_Interface
 */
require_once('Alinks/Zip/Interface.php');

/**
 * Utility class for unzipping archive files
 *
 * A wrapper for the PclZip class. Wrapper setup because I may use
 * the PHP zip functions (when in installed) in the future.
 *
 * Copyright (C) 2008  Sean Hickey
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: Zip.php 386 2008-07-03 05:33:48Z sean $
 * @package Alinks_Zip
 */
class Alinks_Zip implements Alinks_Zip_Interface
{
	/**
	 * The path and name of the zip file
	 *
	 * @var string
	 */
	protected $_file;
	
	/**
	 * Constructor
	 *
	 * @param string $file The path and name of the zip file
	 */
	public function __construct($file = null)
	{
		$this->setFile($file);
	}
	
	/**
	 * Sets the path and name of the file to unzip
	 *
	 * @param string $file The path and name of the zip file
	 * @return Alinks_Zip
	 */
	public function setFile($file)
	{
		$this->_file = $file;
		return $this;
	}
	
	/**
	 * Returns the path and name of the file to unzip
	 *
	 * @return string
	 */
	public function getFile()
	{
		return $this->_file;
	}
	
	/**
	 * Unzips the file to the specified path
	 *
	 * @param string $path The directory where the zip file should
	 * be unarchived.
	 *
	 * @param string $path The path
	 * @return bool
	 */
	public function unzip($path)
	{
		if (!is_writable($path)) {
			/**
			 * @see Alinks_Exception
			 */
			require_once('Alinks/Exception.php');
			throw new Alinks_Exception("The path $path is not writable. Can not unzip $this->_file there.");
		}
		
		if (!class_exists('PclZip')) {
			/**
			 * @see PclZip
			 */
			require_once('Alinks/PclZip.php');
		}
		
		$archive = new PclZip($this->_file);
		if ($archive->extract(PCLZIP_OPT_PATH, $path) == 0) {
			/**
			 * @see Alinks_Exception
			 */
			require_once('Alinks/Exception.php');
			throw new Alinks_Exception("Error unzipping the file $this->_file: " . $archive->errorInfo(true));
		}
		
		return true;
	}
}